/**
 * @fileoverview 用户管理系统交互逻辑
 * @version 1.0.0
 * @license MIT
 * @author DevTeam
 * @lastmodified 2025-09-28
 */

// 全局变量
let currentSearchType = 'username';
let tableBodyType = 'all';

let currentPage = 1;
let totalPages = 1;
let currentPerPage = 10;  // 默认每页显示10条

// 创建分页按钮的函数
function createPagination(paginationContainer, currentPage, totalPages) {
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    let paginationHTML = `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">&lt;</a>
        </li>`;
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
            </li>`;
    }
    paginationHTML += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">&gt;</a>
        </li>`;
    paginationContainer.innerHTML = paginationHTML;
}

async function loadUsers(page = 1) {
    const queryParams = new URLSearchParams({
        page: page,
        per_page: currentPerPage,
        table_type: tableBodyType,
        search_type: currentSearchType,
        query: currentSearchType === 'username' 
            ? document.getElementById('usernameInput').value.trim()
            : document.getElementById('dateInput').value
    });
    try {
        const response = await fetch(`/get_users?${queryParams}`);
        const data = await response.json();
        
        currentPage = data.current_page;
        totalPages = data.total_pages;
        
        // 更新表格
        updateTable(data.users, tableBodyType);
        // 更新分页控件
        const paginationContainers = document.querySelectorAll('.pagination');
        paginationContainers.forEach(container => {
            createPagination(container, currentPage, totalPages);
        });
        // 更新统计信息
        updateResultCount(data.count);
        
    } catch (error) {
        console.error('数据加载失败:', error);
    }
}

// 页码变更事件处理
function changePage(newPage) {
    if (newPage >= 1 && newPage <= totalPages) {
        currentPage = newPage;
        loadUsers(currentPage);
    }
}
// 每页显示数量改变时的处理
function changePerPage(value) {
    currentPerPage = parseInt(value);
    currentPage = 1;  // 重置为第一页
    loadUsers();      // 重新加载数据
}
// 搜索函数
function userNameSearch() {
    currentSearchType = 'username';
    currentPage = 1;
    loadUsers();
}
function dateSearch() {
    currentSearchType = 'date';
    currentPage = 1;
    loadUsers();
}

// 假设我们有一个函数来生成 URL
function generateUrl(route, params = {}) {
    let url = `/${route}`;
    if (Object.keys(params).length > 0) {
        url += '?' + new URLSearchParams(params).toString();
    }
    return url;
}

function updateTable(users, tableBodyType) {
    const tableBody = document.getElementById(tableBodyType + '-users-table-body');

    if (users.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
        return;
    }

    let html = '';
    
    users.forEach((user, index) => {
        const btnClass = user.is_active ? 'btn-warning' : 'btn-success';
        const btnText = user.is_active ? '禁用' : '激活';
        const formattedDate = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(new Date(user.created_at));
        //${new Date(user.created_at).toLocaleString()}
        
        html += `
            <tr>
                <td>${index + 1}</td>
                <td>${user.user_name}</td>
                <td><code>${user.uuid}</code></td>
                <td class="status">
                    <span class="badge ${user.is_active ? 'bg-success' : 'bg-danger'}">
                        ${user.is_active ? '活跃' : '禁用'}
                    </span>
                </td>
                <td>${formattedDate}</td>
                <td>
                    <div class="btn-group btn-group-sm">
                
                        <form method="POST" action="${generateUrl('toggle_status')}">
                            <input type="hidden" name="user_uuid" value="${user.uuid}">
                            <button type="submit" class="btn ${btnClass}">
                                ${btnText}
                            </button>
                        </form>
                        
                        <form method="POST" action="${generateUrl('delete_user')}">
                            <input type="hidden" name="user_uuid" value="${user.uuid}">
                            <button type="submit" class="btn btn-danger" onclick="return confirm('确定要删除此用户吗？')">
                                删除
                            </button>
                        </form>

                        <a data-user-uuid="${user.uuid }" href="javascript:void(0)" class="btn btn-info user-detail-link" title="查看历史记录">
                            <i class="bi bi-clock-history"></i> 详情
                        </a>
                        
                        <form method="POST" action="${generateUrl('download')}">
                            <input type="hidden" name="user_name" value="${user.user_name}">
                            <button type="submit" class="btn btn-success" title="下载秘钥文件">
                                <i class="bi bi-download"></i> 下载
                            </button>
                        </form>
                        
                    </div>
                </td>
            </tr>`;
    });

    tableBody.innerHTML = html;
}

// 更新结果统计
function updateResultCount(count) {
    const resultCount = document.getElementById(tableBodyType + '-search-result');
    const usernameQuery = document.getElementById('usernameInput').value.trim();
    const dateQuery = document.getElementById('dateInput').value;
    
    if (currentSearchType === 'username' && usernameQuery) {
        resultCount.textContent = `找到 ${count} 个匹配"${usernameQuery}"的用户`;
    } else if (currentSearchType === 'date' && dateQuery) {
        resultCount.textContent = `找到 ${count} 个在 ${dateQuery} 创建的用户`;
    } else {
        resultCount.textContent = ``;
    }
}


document.addEventListener('DOMContentLoaded', function () {
    var tabPaneAllUsers = document.getElementById('all-users');
    var tabPaneActiveUsers = document.getElementById('active-users');
    var tabPaneInactiveUsers = document.getElementById('inactive-users');

    loadUsers();

    function updateTableVisibility(tabPaneId) {
        if (tabPaneId === 'all-users') {
            tabPaneAllUsers.classList.add('show', 'active');
            tabPaneActiveUsers.classList.remove('show', 'active');
            tabPaneInactiveUsers.classList.remove('show', 'active');
        } else if (tabPaneId === 'active-users') {
            tabPaneAllUsers.classList.remove('show', 'active');
            tabPaneActiveUsers.classList.add('show', 'active');
            tabPaneInactiveUsers.classList.remove('show', 'active');
        } else if (tabPaneId === 'inactive-users') {
            tabPaneAllUsers.classList.remove('show', 'active');
            tabPaneActiveUsers.classList.remove('show', 'active');
            tabPaneInactiveUsers.classList.add('show', 'active');
        }
    }

    document.getElementById('all-users-tab').addEventListener('click', function () {
        updateTableVisibility('all-users');
        tableBodyType = 'all';
    });

    document.getElementById('active-users-tab').addEventListener('click', function () {
        updateTableVisibility('active-users');
        tableBodyType = 'active';
    });

    document.getElementById('inactive-users-tab').addEventListener('click', function () {
        updateTableVisibility('inactive-users');
        tableBodyType = 'inactive';
    });

    // 回车键搜索
    document.getElementById('usernameInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            userNameSearch();
        }
    });

    document.getElementById('dateInput').addEventListener('change', function() {
        if (currentSearchType === 'date') {
            dateSearch();
        }
    });

    // 清空搜索框时显示所有用户
    document.getElementById('usernameInput').addEventListener('input', function() {
        if (this.value.trim() === '') {
            userNameSearch();
        }
    });


    // 获取模态框元素
    var modal = document.getElementById('createUserModal');
    // 获取 Bootstrap Modal 实例
    var bootstrapModal = new bootstrap.Modal(modal);
    // 监听模态框显示事件
    modal.addEventListener('show.bs.modal', function (event) {
        modal.setAttribute('aria-hidden', 'false');
    });
    // 监听模态框隐藏事件
    modal.addEventListener('hidden.bs.modal', function (event) {
        modal.setAttribute('aria-hidden', 'true');
    });

});

document.addEventListener('click', async function (e) {
    const link = e.target.closest('.user-detail-link');
    if (link) {
        e.preventDefault(); // 防止链接默认行为

        const uuid = link.dataset.userUuid;
        window.currentUserUuid = link.dataset.userUuid;

        // 获取需要更新的元素
        const detailElements = {
            username: document.getElementById('detail-username'),
            uuid: document.getElementById('detail-uuid'),
            statusBadge: document.getElementById('detail-status'),
            created: document.getElementById('detail-created'),
            historyCount: document.getElementById('detail-history-count'),
            historyTable: document.getElementById('history-table'),
            noHistoryAlert: document.getElementById('no-history-alert')
        };

        var statusToggleBtn = document.getElementById('status-toggle-btn')

        // 显示加载状态
        for (let key in detailElements) {
            if (key !== 'historyTable' && key !== 'noHistoryAlert') {
                detailElements[key].textContent = '加载中...';
            }
        }

        try {
            // 请求后端API
            const response = await fetch(`/api/user/${uuid}/details`);
            if (!response.ok) {
                throw new Error(`HTTP 错误！状态码：${response.status}`);
            }
            const { user, history } = await response.json();

            // 更新基本信息
            detailElements.username.textContent = user.user_name;
            detailElements.uuid.textContent = user.uuid;
            detailElements.statusBadge.className = `badge bg-${user.is_active ? 'success' : 'danger'}`;
            detailElements.statusBadge.textContent = user.is_active ? '活跃' : '禁用';
            detailElements.created.textContent = user.created_at;
            detailElements.historyCount.textContent = history.length;

            statusToggleBtn.classList.remove('btn-success', 'btn-warning');
            statusToggleBtn.classList.add(user.is_active ? 'btn-warning' : 'btn-success');
            statusToggleBtn.textContent = user.is_active ? '禁用' : '激活';
            statusToggleBtn.dataset.userUuid = user.uuid;

            document.getElementById('deleteUserUUID').value = uuid;
            document.getElementById('downloadCryptoUsername').value = user.user_name;

            // 更新历史记录
            const tbody = document.querySelector('#history-table tbody');
            tbody.innerHTML = history.map(h => `
                    <tr>
                        <td>${h.timestamp}</td>
                        <td>${h.action}</td>
                        <td>${h.details}</td>
                    </tr>
                `).join('');

            // 控制表格可见性
            detailElements.historyTable.classList.toggle('d-none', !history.length);
            detailElements.noHistoryAlert.classList.toggle('d-none', history.length);

            // 手动打开侧边栏
            new bootstrap.Offcanvas('#offcanvasRight').show();

        } catch (error) {
            console.error('加载失败:', error);
            alert('数据加载失败，请重试');
        }
    }

    

});


function toggleStatus() {
        
    fetch('/api/toggle_status', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            user_uuid: window.currentUserUuid
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新侧边栏状态显示
            const statusBadge = document.getElementById('detail-status');
            statusBadge.textContent = data.new_status ? '活跃' : '禁用';
            statusBadge.className = `badge bg-${data.new_status ? 'success' : 'danger'}`;
            
            // 更新操作按钮状态
            const toggleBtn = document.getElementById('status-toggle-btn');
            toggleBtn.textContent = data.new_status ? '禁用' : '激活';
            toggleBtn.className = `btn btn-${data.new_status ? 'warning' : 'success'}`;
            
            // 同步更新用户列表（需要根据实现方式调整）
            updateUserList(data.updated_user);
        }
    });
}

function updateUserList(updatedUser) {
    // 更新所有相关列表中的用户状态
    document.querySelectorAll(`tr[data-user-uuid='${updatedUser.uuid}']`).forEach(row => {
        const badge = row.querySelector('.status .badge');
        badge.textContent = updatedUser.is_active ? '活跃' : '禁用';
        badge.className = `badge bg-${updatedUser.is_active ? 'success' : 'danger'}`;
    });
}